package com.qianchang.microfinance.view.dialog;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.bigkoo.pickerview.OptionsPickerView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.AreaJsonBean;
import com.qianchang.microfinance.utils.GetJsonDataUtil;

import java.util.ArrayList;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: <地区选择>
 * 修 改 人: sushuo
 * 修改时间: 2017-3-21
 */

public class AreaDialog extends BaseDialog {

    private Context context;
    private OptionsPickerView pvOptions;
    private AsyncTask<Void, Void, String> mTask;

    private ArrayList<AreaJsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<AreaJsonBean.CityBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<AreaJsonBean.AreaBean>>> options3Items = new ArrayList<>();
    private OnAreaSelectListener onAreaSelectListener;

    private String title;

    public AreaDialog(final Context context) {
        this.context = context;
        mTask = new AsyncTask<Void, Void, String>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

            }

            @Override
            protected String doInBackground(Void... voids) {
                initJsonData();
                return "OK";
            }

            @Override
            protected void onPostExecute(String result) {
                initPickerView();
            }
        };
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTitle() {
        return TextUtils.isEmpty(title) ? "选择省市区" : title;
    }

    public void showPickerView() {
        if (pvOptions == null) {
            if (mTask.getStatus() != AsyncTask.Status.RUNNING)
                mTask.execute();
        } else {
            pvOptions.show();
        }
    }

    public void initPickerView() {
        if (null == options1Items || options2Items == null || options3Items == null) {
            return;
        }
        pvOptions = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                if (onAreaSelectListener != null) {
                    StringBuilder builder = new StringBuilder();
                    String province = options1Items.get(options1).getName();
                    String city = options2Items.get(options1).get(options2).getName();
                    String area = options3Items.get(options1).get(options2).get(options3).getName();
                    builder.append(province);
                    if (!TextUtils.isEmpty(province) && province.equals(city)) {
                        builder.append(area);
                    } else {
                        builder.append(city).append(area);
                    }
                    onAreaSelectListener.onAreaSelect(options1Items.get(options1).getId(),
                            options2Items.get(options1).get(options2).getId(),
                            options3Items.get(options1).get(options2).get(options3).getId(), builder.toString());
                }
            }
        }).setTitleColor(context.getResources().getColor(R.color.common_black_color_3))
                .setTitleText(getTitle())
                .setDividerColor(context.getResources().getColor(R.color.line_color))
                .setTextColorCenter(context.getResources().getColor(R.color.common_black_color_3)) //设置选中项文字颜色
                .setCancelColor(context.getResources().getColor(R.color.common_black_color_6))
                .setContentTextSize(16)
                /*.setTypeface(Typeface.DEFAULT_BOLD)//加粗字体*/
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/

        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器

        View currentFocus = ((Activity) context).getCurrentFocus();
        if (null != currentFocus) {
            ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(currentFocus.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
        pvOptions.show();
    }

    public void initJsonData() {//解析数据
        parseAreaJson();

        for (int i = 0; i < options1Items.size(); i++) {//遍历省份
            ArrayList<AreaJsonBean.CityBean> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<AreaJsonBean.AreaBean>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < options1Items.get(i).getChildren().size(); c++) {//遍历该省份的所有城市
                cityList.add(options1Items.get(i).getChildren().get(c));//添加城市
                parseAreaList(i, province_AreaList, c);
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }
    }

    public void parseAreaJson() {
        //获取assets目录下的json文件数据
        if (null == options1Items || options1Items.size() == 0) {
            //用Gson 转成实体
            options1Items = GetJsonDataUtil.newInstance().parseData();
        }
    }

    private void parseAreaList(int i, ArrayList<ArrayList<AreaJsonBean.AreaBean>> province_AreaList, int c) {
        ArrayList<AreaJsonBean.AreaBean> city_AreaList = new ArrayList<>();//该城市的所有地区列表

        //如果无地区数据，建议添加空数据，防止数据为null 导致三个选项长度不匹配造成崩溃
        if (options1Items.get(i).getChildren().get(c).getChildren().size() == 0) {
            AreaJsonBean.AreaBean areaBean = new AreaJsonBean.AreaBean();
            areaBean.setName("");
            city_AreaList.add(areaBean);
        }
        for (int d = 0; d < options1Items.get(i).getChildren().get(c).getChildren().size(); d++) {//该城市对应地区所有数据
            city_AreaList.add(options1Items.get(i).getChildren().get(c).getChildren().get(d));//添加该城市所有地区数据
        }
        province_AreaList.add(city_AreaList);//添加该省所有地区数据
    }


    public void setOnAreaSelectListener(OnAreaSelectListener onAreaSelectListener) {
        this.onAreaSelectListener = onAreaSelectListener;
    }

    public interface OnAreaSelectListener {
        void onAreaSelect(String proviceId, String cityId, String areaId, String result);
    }

}

